package socket.processor;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ignite.entity.Person;
import org.smartboot.socket.MessageProcessor;
import org.smartboot.socket.StateMachineEnum;
import org.smartboot.socket.transport.AioSession;
import org.smartboot.socket.transport.WriteBuffer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import socket.service.PersonService;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class SmartSocketProcessor implements MessageProcessor<String> {
    @Resource
    private PersonService personService;
    /**
     * 日志
     */

    /**
     * 存放所有的客户端
     */
    private final Map<String, AioSession> sessionMap = new ConcurrentHashMap<>();

    @Override
    public void process(AioSession session, String msg) {
        toClients(session, msg, false);
    }

    @Override
    public void stateEvent(AioSession session, StateMachineEnum stateMachineEnum, Throwable throwable) {
        switch (stateMachineEnum) {
            case NEW_SESSION:
                log.info("客户端:{} 建立连接", session.getSessionID());
                sessionMap.put(session.getSessionID(), session);
                break;
            case SESSION_CLOSED:
                log.info("客户端:{} 断开连接", session.getSessionID());
                sessionMap.remove(session.getSessionID());
                break;
            default:
        }
    }

    /**
     * 广播
     *
     * @param session  客户端
     * @param msg      推送消息
     * @param pushSelf 是否广播自己 默认 false
     */
    public void toClients(AioSession session, String msg, boolean pushSelf) {
        log.info("收到消息：{}：{}", session.getSessionID(), msg);
        byte[] bytes = msg.getBytes();
//        Person person = JSON.parseObject(msg, Person.class);
//        log.info("消息解析：{}",person);
        List<Person> personList = personService.getByName(msg);
        log.info("{openFeign查询：}", personList);
        WriteBuffer writeBuffer = session.writeBuffer();
        try {
            log.info("推送消息：{}：{}", session.getSessionID(), personList);
            String personStr = personList.toString();
            writeBuffer.writeInt(personStr.length());
            writeBuffer.write(personStr.getBytes(StandardCharsets.UTF_8));
            writeBuffer.flush();
        } catch (Exception e) {
            log.error("推送消息异常：{} ：", session.getSessionID(), e);
        }
    }
}
